<?php
class Dig_View_Helper_LinkList extends Zend_View_Helper_Abstract
{
    /**
     * the link list helper renders an html list of links
     * 
     * usage:
     * $linkTemplate = "<a href='/post/open/id/{id}'>{headline}</a>";
     * echo $this->linkList($this->posts, $linkTemplate);
     *
     * @param mixed $model, the data to iterate through
     * @param string $linkTemplate, the template for the link. wrap each dynamic field with curly braces eg: {id}
     * @param array $fields, these are the fields to replace in the link
     * @param unknown_type $options
     */
    public function linkList ($model, $linkTemplate, $options = array())
    {
        if ($model) {
            $templateVariables = $this->_parseTemplate($linkTemplate);
            foreach ($model as $row) {
                $link = $linkTemplate;
                foreach ($templateVariables as $variable) {
                    if (is_object($row)) {
                        $value = $row->$variable;
                    } else {
                        $value = $row[$variable];
                    }
                    $link = str_replace('{' . $variable . '}', $value, $link);
                }
                $links[] = $link;
            }
            if (count($links) > 0) {
                return $this->view->htmlList($links, null, $options, false);
            }
        }
        return false;
    }
    /**
     * this method matches all of the placeholders in a template 
     * the placeholders are wrapped in {curly_braces}
     * it returns an array of the fields to replace
     *
     * @param string $template
     */
    protected function _parseTemplate ($template)
    {
        $pattern = "#(\{)(.*?)(\})#i";
        preg_match_all($pattern, $template, $matches);
        return $matches[2];
    }
}
?>